package com.hqyj.freemovie.front.service.impl;

import com.hqyj.freemovie.front.view.Students;
import com.hqyj.freemovie.front.repository.StudentsRepository;
import com.hqyj.freemovie.front.service.StudentsService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

@Service
public class StudentsServiceImpl implements StudentsService {

    @Resource
    private StudentsRepository studentsRepository;

    @Transactional
    @Override
    public Students save(Students s) throws Exception {
        return studentsRepository.save(s);
    }


    @Transactional
    @Override
    public boolean saveBatch(List<Students> studentsList) throws Exception {
        try {
            studentsRepository.saveAll(studentsList);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Transactional
    @Override
    public Students update(Students s) throws Exception {
        return studentsRepository.save(s);
    }

    @Override
    public Students queryStudentBySid(String sid) {
        Optional<Students> optional = studentsRepository.findById(sid);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    @Override
    public List<Students> queryAllStudents() {
        //return (List<Students>) studentsRepository.findAll();
        List<Students> studentsList = new ArrayList<Students>();
        Iterable<Students> it = studentsRepository.findAll();
        for (Students students : it) {
            studentsList.add(students);
        }
        return studentsList;
    }

    @Transactional
    @Override
    public boolean removeStudent(String sid) throws Exception {
        try {
            studentsRepository.deleteById(sid);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }

    @Override
    public Page elasticSearchByKeyword(String keyword) {
        //0,表示查询第一页，每页10条记录。
        Pageable pager = PageRequest.of(0,10);
        return studentsRepository.elasticsearchMoviesByKeyWords(keyword,pager);
    }
}
